﻿#include "MultPlot.h"
#include "ui_MultPlot.h"

MultPlot::MultPlot(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MultPlot)
    ,m_isShowTracer(false)
    ,m_xTracer(Q_NULLPTR)
    ,m_yTracer(Q_NULLPTR)
    ,m_dataTracers(QList<XxwTracer *>())
    ,m_lineTracer(Q_NULLPTR)
{
    ui->setupUi(this);
    initUIs();
    ui->widget->setMouseTracking(true);
    this->installEvent(true);
}

MultPlot::~MultPlot()
{
    delete ui;
}

QCustomPlot *MultPlot::getBody()
{
    return ui->widget;
}

void MultPlot::creatChart(int xInd,int yInd,std::string x,std::string y)
{
    ui->widget->graph(DATA_POINT)->setPen(QPen(Qt::green));
    ui->widget->graph(DATA_POINT)->setLineStyle(QCPGraph::lsNone);
    ui->widget->graph(DATA_POINT)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssDisc, 3));

    for(int i =0;i< curData[0].size();i++){
        ui->widget->graph(DATA_POINT)->addData(curData[xInd].at(i), curData[yInd].at(i));
    }
    ui->widget->xAxis->setLabel(XLable);        //QStringLiteral(XLable));          //X轴文字显示
    ui->widget->yAxis->setLabel(YLable);        //QStringLiteral(XLable));        //Y轴文字显示
    ui->widget->graph(DATA_POINT)->rescaleAxes();
    ui->widget->graph(DATA_POINT)->rescaleAxes(true);

    ui->widget->replot();
}

void MultPlot::initUIs()
{
    // 设置背景色
    ui->widget->setBackground(QBrush(BACKGROUND_COLOR));

    // 设置坐标轴颜色
    ui->widget->xAxis->setTickLabelColor(TEXT_COLOR);
    ui->widget->yAxis->setTickLabelColor(TEXT_COLOR);
    xAxis.reset(new QCPAxisTickerFixed);
    yAxis.reset(new QCPAxisTickerFixed);

    ui->widget->xAxis->setTicker(xAxis);
    ui->widget->yAxis->setTicker(yAxis);

    xAxis->setScaleStrategy(QCPAxisTickerFixed::ssMultiples);
    yAxis->setScaleStrategy(QCPAxisTickerFixed::ssMultiples);
    yAxis->setTickStepStrategy(QCPAxisTicker::tssMeetTickCount);
    xAxis->setTickStepStrategy(QCPAxisTicker::tssReadability);
    ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);   //可拖拽+可滚轮缩放
    ui->widget->addGraph();
    // ui->widget->addGraph();

    ui->widget->legend->setVisible(true);

    // add title layout element:
    ui->widget->plotLayout()->insertRow(0);
    title.reset(new QCPTextElement(ui->widget, Title, QFont("黑体", 12, QFont::Bold)));
    ui->widget->plotLayout()->addElement(0, 0, title.data());
    QFont legendFont = font();  // start out with MainWindow's font..
    legendFont.setPointSize(9); // and make a bit smaller for legend
    ui->widget->legend->setFont(legendFont);
    ui->widget->legend->setBrush(QBrush(QColor(255,255,255,230)));

    ui->widget->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignTop |Qt::AlignRight);

    // make left and bottom axes always transfer their ranges to right and top axes:
    connect(ui->widget->xAxis, SIGNAL(rangeChanged(QCPRange)), ui->widget->xAxis2, SLOT(setRange(QCPRange)));
    connect(ui->widget->yAxis, SIGNAL(rangeChanged(QCPRange)), ui->widget->yAxis2, SLOT(setRange(QCPRange)));

    // Allow user to drag axis ranges with mouse, zoom with mouse wheel and select graphs by clicking:
    ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);

}


/*********************     鼠标移动    ********************/
bool MultPlot::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->widget && event->type() == QEvent::MouseMove && m_isShowTracer) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        //当前鼠标位置（像素坐标）
        int x_pos = mouseEvent->pos().x();
        int y_pos = mouseEvent->pos().y();

        //像素坐标转成实际的x,y轴的坐标
        float x_val = ui->widget->xAxis->pixelToCoord(x_pos);
        float y_val = ui->widget->yAxis->pixelToCoord(y_pos);

        if(Q_NULLPTR == m_xTracer)
            m_xTracer = new XxwTracer(ui->widget, XxwTracer::XAxisTracer);//x轴
        m_xTracer->updatePosition(x_val, y_val);

        if(Q_NULLPTR == m_yTracer)
            m_yTracer = new XxwTracer(ui->widget, XxwTracer::YAxisTracer);//y轴
        m_yTracer->updatePosition(x_val, y_val);

        int nTracerCount = m_dataTracers.count();
        int nGraphCount = 1;  // graphCount();
        if(nTracerCount < nGraphCount)
        {
            for(int i = nTracerCount; i < nGraphCount; ++i)
            {
                XxwTracer *tracer = new XxwTracer(ui->widget, XxwTracer::DataTracer);
                m_dataTracers.append(tracer);
            }
        }
        else if(nTracerCount > nGraphCount)
        {
            for(int i = nGraphCount; i < nTracerCount; ++i)
            {
                XxwTracer *tracer = m_dataTracers[i];
                if(tracer)
                {
                    tracer->setVisible(false);
                }
            }
        }
        for (int i = 0; i < nGraphCount; ++i)
        {
            XxwTracer *tracer = m_dataTracers[i];
            if(!tracer)
                tracer = new XxwTracer(ui->widget, XxwTracer::DataTracer);
            tracer->setVisible(true);
            tracer->setPen(ui->widget->graph(i)->pen());
            tracer->setBrush(Qt::NoBrush);
            tracer->setLabelPen(ui->widget->graph(i)->pen());
            double value = ui->widget->graph(i)->data()->findBegin(x_val)->value;
            tracer->updatePosition(x_val, value);
        }

        if(Q_NULLPTR == m_lineTracer)
            m_lineTracer = new XxwTraceLine(ui->widget,XxwTraceLine::Both);//直线
        m_lineTracer->updatePosition(x_val, y_val);

        ui->widget->replot();//曲线重绘
    }else{
        return QObject::eventFilter(watched, event);
    }

    return true;
}
#if 0
void MultPlot::mouseMoveEvent(QMouseEvent *event)
{
    // QCustomPlot::mouseMoveEvent(event);
    ui->widget->mouseMove(event);
    if(m_isShowTracer && event->type() == QEvent::MouseMove)
    {
        //当前鼠标位置（像素坐标）
        int x_pos = event->pos().x();
        int y_pos = event->pos().y();

        //像素坐标转成实际的x,y轴的坐标
        float x_val = ui->widget->xAxis->pixelToCoord(x_pos);
        float y_val = ui->widget->yAxis->pixelToCoord(y_pos);

        if(Q_NULLPTR == m_xTracer)
            m_xTracer = new XxwTracer(ui->widget, XxwTracer::XAxisTracer);//x轴
        m_xTracer->updatePosition(x_val, y_val);

        if(Q_NULLPTR == m_yTracer)
            m_yTracer = new XxwTracer(ui->widget, XxwTracer::YAxisTracer);//y轴
        m_yTracer->updatePosition(x_val, y_val);

        int nTracerCount = m_dataTracers.count();
        int nGraphCount = 1;
        if(nTracerCount < nGraphCount)
        {
            for(int i = nTracerCount; i < nGraphCount; ++i)
            {
                XxwTracer *tracer = new XxwTracer(ui->widget, XxwTracer::DataTracer);
                m_dataTracers.append(tracer);
            }
        }
        else if(nTracerCount > nGraphCount)
        {
            for(int i = nGraphCount; i < nTracerCount; ++i)
            {
                XxwTracer *tracer = m_dataTracers[i];
                if(tracer)
                {
                    tracer->setVisible(false);
                }
            }
        }
        for (int i = 0; i < nGraphCount; ++i)
        {
            XxwTracer *tracer = m_dataTracers[i];
            if(!tracer)
                tracer = new XxwTracer(ui->widget, XxwTracer::DataTracer);
            tracer->setVisible(true);
            tracer->setPen(ui->widget->graph(i)->pen());
            tracer->setBrush(Qt::NoBrush);
            tracer->setLabelPen(ui->widget->graph(i)->pen());
            double value = ui->widget->graph(i)->data()->findBegin(x_val)->value;
            tracer->updatePosition(x_val, value);
        }

        if(Q_NULLPTR == m_lineTracer)
            m_lineTracer = new XxwTraceLine(ui->widget,XxwTraceLine::Both);//直线
        m_lineTracer->updatePosition(x_val, y_val);

        ui->widget->replot();//曲线重绘
    }

}

#endif

void MultPlot::setTitles(std::string t1, std::string t2)
{
    ui->widget->graph(0)->setName(QString::fromStdString(t1));
//    ui->widget->graph(1)->setName(QString::fromStdString(t2));
//    assisLine->point1->setCoords(ui->widget->xAxis->range().lower, ui->widget->yAxis->range().lower);
//    assisLine->point2->setCoords(ui->widget->xAxis->range().upper, ui->widget->yAxis->range().lower);
    ui->widget->replot();//曲线重绘


}

void MultPlot::SetStyle(StyleDraw s)
{
    auto it = QCPGraph::lsLine;
    switch (s) {
    case S_NONE:{
        it = QCPGraph::lsNone;
        break;
    }
    case S_LINE:
        it = QCPGraph::lsLine;
        break;
    }
    ui->widget->graph(DATA_POINT)->setLineStyle(it);
}

void MultPlot::installEvent(bool v)
{
    if(v){
        // 注册监听事件
        ui->widget->installEventFilter(this);
    }else{
        // 注册监听事件
        ui->widget->removeEventFilter(this);
    }
}

void MultPlot::SetGridVisible(bool v)
{
    ui->widget->yAxis->grid()->setSubGridVisible(v);
    ui->widget->yAxis->grid()->setSubGridVisible(v);
    ui->widget->replot();
}

